<?php

declare(strict_types=1);

namespace App\Service;

/**
 * Class DeliveryRuleAreaService
 * @package App\Service
 */
class DeliveryRuleAreaService extends BaseService
{
    /**
     * 获取商家运费规则地址ID
     * @param int $tpl_id
     * @param int $city_id
     * @param int $street_id
     * @param int $province_id
     * @return int
     */
    public function getRulesIdByPCS(int $tpl_id, int $province_id = 0, int $city_id = 0, int $street_id = 0): int
    {
        if (empty($province_id) || empty($tpl_id)) {
            return 0;
        }
        $rule_id = $this->getModelInstance()
            ->leftJoin('fly_delivery_tpl', 'fly_delivery_tpl.id', '=', 'fly_delivery_rule_area.tpl_id')
            ->where(['area_id' => $street_id, 'fly_delivery_tpl.id' => $tpl_id])
            ->select(['fly_delivery_rule_area.rule_id'])
            ->first();
        if (empty($rule_id)) {
            $rule_id = $this->getModelInstance()
                ->leftJoin('fly_delivery_tpl', 'fly_delivery_tpl.id', '=', 'fly_delivery_rule_area.tpl_id')
                ->where(['area_id' => 0, 'city_id' => $city_id, 'fly_delivery_tpl.id' => $tpl_id])
                ->select(['fly_delivery_rule_area.rule_id'])
                ->first();
            if (empty($rule_id)) {
                $rule_id = $this->getModelInstance()
                    ->leftJoin('fly_delivery_tpl', 'fly_delivery_tpl.id', '=', 'fly_delivery_rule_area.tpl_id')
                    ->where(['area_id' => 0, 'city_id' => 0, 'province_id' => $province_id, 'fly_delivery_tpl.id' => $tpl_id])
                    ->select(['fly_delivery_rule_area.rule_id'])
                    ->first();
            }
        }
        return empty($rule_id) ? 0 : $rule_id->rule_id;
    }

}